package com.jusfoun.communication.service;

import com.jusfoun.communication.dao.AutoReplyDao;
import com.jusfoun.communication.model.AutoReply;
import com.jusfoun.communication.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 自动回复相关service
 *
 * @author player six
 * @email jslcylcy@163.com
 * @create 2017-12-11 16:29
 **/
@Service
public class AutoReplyService {

    private static final Logger logger = LoggerFactory.getLogger(AutoReplyService.class);

    @Autowired
    private ResultUtil resultUtil;

    @Autowired
    private AutoReplyDao autoReplyDao;

    /**
     * 查询分页自动回复信息
     *
     * @param appId
     * @param pageVo
     * @return
     */
    public PageInfo<AutoReply> list(String appId, PageVo pageVo) {
        long size = autoReplyDao.listCount(appId);
        if (size > 0) {
            PageInfo<AutoReply> autoReplyPageInfo = new PageInfo<>(pageVo.getPage(), pageVo.getRows(), size);
            autoReplyPageInfo.setList(autoReplyDao.list(appId, autoReplyPageInfo));
            autoReplyPageInfo.calSize();
            return autoReplyPageInfo;
        } else {
            logger.info("appId: " + appId + "没有自动回复设置");
        }
        return new PageInfo<>();
    }

    /**
     * 新增autoReply
     *
     * @param autoReply
     * @return
     */
    private AutoReply addAutoReplyRedis(AutoReply autoReply) {
        return autoReplyDao.add(autoReply);
    }

    /**
     * 新增autoReply
     *
     * @param autoReply
     * @return
     */
    private AutoReply updateAutoReplyRedis(AutoReply autoReply) {
        return autoReplyDao.update(autoReply);
    }

    /**
     * 是否启用 自动回复
     *
     * @param appId
     * @return
     */
    public boolean isUseAutoReply(String appId) {
        return autoReplyDao.isUseAutoReply(appId);
    }

    /**
     * 自动回复开始时间
     *
     * @param appId
     * @return
     */
    public String getBeginTime(String appId) {
        return autoReplyDao.getAutoReplyBeginTime(appId);
    }

    /**
     * 自动回复结束时间
     *
     * @param appId
     * @return
     */
    public String getEndTime(String appId) {
        return autoReplyDao.getAutoReplyEndTime(appId);
    }

    /**
     * 保存自动回复配置信息
     *
     * @param appId
     * @param useAutoReply
     * @param autoReplyBegin
     * @param autoReplyEnd
     * @return
     */
    public Result saveConfigure(String appId, boolean useAutoReply, String autoReplyBegin, String autoReplyEnd) {
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(autoReplyBegin) || StringUtils.isBlank(autoReplyEnd)) {
            return resultUtil.fail("失败", "参数有误");
        }
        autoReplyDao.saveConfigure(appId, useAutoReply, autoReplyBegin, autoReplyEnd);
        return resultUtil.success();
    }

    /**
     * 新增自动回复规则
     *
     * @param autoReply
     * @return
     */
    public Result addAutoReply(AutoReply autoReply) {
        if (StringUtils.isBlank(autoReply.getAppId()) || StringUtils.isBlank(autoReply.getContent()) || null == autoReply.getLevel()) {
            return resultUtil.fail("失败", "参数有误");
        }
        addAutoReplyRedis(autoReply);
        return resultUtil.success();
    }

    /**
     * 更新自动回复规则
     *
     * @param autoReply
     * @return
     */
    public Result updateAutoReply(AutoReply autoReply) {
        if (null == autoReply.getId()) {
            return resultUtil.fail("失败", "id不能为空");
        }
        if (StringUtils.isBlank(autoReply.getAppId()) || StringUtils.isBlank(autoReply.getContent()) || null == autoReply.getLevel()) {
            return resultUtil.fail("失败", "参数有误");
        }
        updateAutoReplyRedis(autoReply);
        return resultUtil.success();
    }

    /**
     * 批量删除
     *
     * @param idList
     * @param appId
     * @return
     */
    public Result delAutoReply(List<Long> idList, String appId) {
        if (StringUtils.isBlank(appId) || idList == null || idList.isEmpty()) {
            return resultUtil.fail("失败", "参数有误");
        }
        for (Long id : idList) {
            autoReplyDao.delById(appId, id);
        }
        return resultUtil.success();
    }

    /**
     * 根据过滤规则获取自动回复list
     *
     * @param appId
     * @param date
     * @return
     */
    public List<AutoReply> listAutoReplyByAppIdAndTime(String appId, Date date) {
        //校验是否启用自动回复
        if (!autoReplyDao.isUseAutoReply(appId)) {
            return null;
        }
        //是否在自动回复时间内
        if (!checkAutoReply(date, autoReplyDao.getAutoReplyBeginTime(appId), autoReplyDao.getAutoReplyEndTime(appId))) {
            return null;
        }
        List<AutoReply> autoReplyList = autoReplyDao.listAll(appId);
        if (autoReplyList != null) {
            sortAutoReplyList(autoReplyList);
            return autoReplyList;
        }
        return null;
    }

    private void sortAutoReplyList(List<AutoReply> autoReplyList) {
        Collections.sort(autoReplyList, (o1, o2) -> {
            if (o1 == null) {
                return 1;
            }
            if (o2 == null) {
                return -1;
            }
            if (o1.getLevel() == null) {
                return 1;
            }
            if (o2.getLevel() == null) {
                return -1;
            }
            return o1.getLevel().compareTo(o2.getLevel());
        });
    }

    /**
     * 校验是否回复自动回复的时间段
     *
     * @param date
     * @param begin 自动回复开始时间
     * @param end   自动回复结束时间
     * @return
     */
    private boolean checkAutoReply(Date date, String begin, String end) {
        if (StringUtils.isBlank(begin) || StringUtils.isBlank(end) || date == null) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        try {
            Date beginDate = sdf.parse(begin);
            Date endDate = sdf.parse(end);
            date = sdf.parse(sdf.format(date));
            return compareDate(date, beginDate, endDate);
        } catch (ParseException e) {
            logger.error("解析时间出错", e);
        }
        return false;

    }

    private boolean compareDate(Date date, Date beginDate, Date endDate) {
        int compare = beginDate.compareTo(endDate);
        if (compare == 0) {
            return true;
        } else if (compare < 0) {
            return date.after(beginDate) && date.before(endDate);
        } else {
            return date.before(endDate) || date.after(beginDate);
        }
    }
}
